package com.zf.zfed.audit.ui

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.Switch
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.zf.zfed.audit.R

/**
 * 存储空间告警设置项控件
 * 结合开关和下拉选择功能
 */
@SuppressLint("ResourceAsColor", "RtlHardcoded")
class StorageAlarmSetItem @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    
    // 图标
    private var itemIcon: ImageView
    
    // 名称
    private var itemName: TextView
    
    // 开关
    private var switchView: Switch
    
    // 右侧文字（存储空间大小）
    private var rightText: TextView
    
    // 下拉菜单
    private var popupWindow: PopupWindow? = null
    
    // 存储空间选项列表
    private var storageOptions: List<String> = listOf("2GB", "4GB", "8GB", "10GB", "12GB", "16GB")
    
    // 当前选中的存储空间大小
    private var selectedStorage: String = "2GB"
    
    // 存储空间变化监听器
    private var onStorageChangeListener: ((String) -> Unit)? = null
    
    // 开关变化监听器
    private var onSwitchChangeListener: ((Boolean) -> Unit)? = null

    init {
        isClickable = true
        isFocusable = true
        orientation = VERTICAL
        
        // 设置卡片背景
        background = ContextCompat.getDrawable(context, R.drawable.card_background)
        
        // 设置卡片边距
        val cardPadding = context.dpFromDimen(R.dimen.spacing_8)
        setPadding(cardPadding, cardPadding, cardPadding, cardPadding)

        // 内嵌布局
        val nestedFrameLayout = FrameLayout(context)
        val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F)
        addView(nestedFrameLayout, layoutParams)

        // 图标
        itemIcon = ImageView(context)
        val iconSize = context.dpFromDimen(R.dimen.size_22)
        val iconLP = FrameLayout.LayoutParams(iconSize, iconSize)
        iconLP.gravity = Gravity.START or Gravity.CENTER_VERTICAL
        iconLP.leftMargin = context.dpFromDimen(R.dimen.spacing_16)
        itemIcon.scaleType = ImageView.ScaleType.CENTER_INSIDE
        nestedFrameLayout.addView(itemIcon, iconLP)

        // 文案
        itemName = TextView(context)
        itemName.setTextColor(ContextCompat.getColor(context, R.color.text_primary))
        itemName.textSize = context.spFromDimen(R.dimen.font_20)
        itemName.setTypeface(null, android.graphics.Typeface.BOLD)
        val textLP = FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        textLP.gravity = Gravity.START or Gravity.CENTER_VERTICAL
        textLP.leftMargin = context.dpFromDimen(R.dimen.spacing_50)
        nestedFrameLayout.addView(itemName, textLP)

        // 开关
        switchView = Switch(context)
        switchView.isClickable = false
        switchView.trackDrawable = ContextCompat.getDrawable(context, R.drawable.switch_track)
        switchView.thumbDrawable = ContextCompat.getDrawable(context, R.drawable.switch_thumb)
        val switchLP = FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        switchLP.gravity = Gravity.END or Gravity.CENTER_VERTICAL
        switchLP.marginEnd = context.dpFromDimen(R.dimen.spacing_80)
        nestedFrameLayout.addView(switchView, switchLP)
        
        // 右侧文字（存储空间大小）
        rightText = TextView(context)
        rightText.setTextColor(ContextCompat.getColor(context, R.color.text_primary))
        rightText.textSize = context.spFromDimen(R.dimen.font_14)
        rightText.isClickable = true
        rightText.isFocusable = true
        val rightTextLP = FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        rightTextLP.gravity = Gravity.END or Gravity.CENTER_VERTICAL
        rightTextLP.marginEnd = context.dpFromDimen(R.dimen.spacing_16)
        nestedFrameLayout.addView(rightText, rightTextLP)
        
        // 设置右侧文字点击监听器
        rightText.setOnClickListener {
            if (switchView.isChecked) {
                showStorageDropdown()
            }
        }

        // 设置整体点击监听器
        setOnClickListener {
            if (rightText.isPressed) {
                // 如果点击的是右侧文字区域，显示下拉菜单
                if (switchView.isChecked) {
                    showStorageDropdown()
                }
            } else {
                // 如果点击的是其他区域，切换开关状态
                switchView.isChecked = !switchView.isChecked
                onSwitchChangeListener?.invoke(switchView.isChecked)
            }
        }

        if (attrs != null) {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.StorageAlarmSetItem)
            val title = typedArray.getString(R.styleable.StorageAlarmSetItem_storage_title)
            val iconRes = typedArray.getResourceId(R.styleable.StorageAlarmSetItem_storage_icon, 0)
            val rightTextStr = typedArray.getString(R.styleable.StorageAlarmSetItem_storage_right_text)
            val isChecked = typedArray.getBoolean(R.styleable.StorageAlarmSetItem_storage_checked, false)
            
            itemName.text = title
            rightText.text = rightTextStr ?: selectedStorage
            selectedStorage = rightTextStr ?: selectedStorage
            switchView.isChecked = isChecked
            
            if (iconRes != 0) {
                itemIcon.setImageResource(iconRes)
                itemIcon.visibility = VISIBLE
                itemIcon.setColorFilter(ContextCompat.getColor(context, R.color.text_primary))
            } else {
                itemIcon.visibility = GONE
            }
            
            typedArray.recycle()
        } else {
            itemIcon.visibility = GONE
            switchView.isChecked = false
        }
    }

    /**
     * 设置存储空间选项列表
     */
    fun setStorageOptions(options: List<String>) {
        this.storageOptions = options
    }

    /**
     * 设置当前选中的存储空间大小
     */
    fun setSelectedStorage(storage: String) {
        selectedStorage = storage
        rightText.text = storage
    }

    /**
     * 获取当前选中的存储空间大小
     */
    fun getSelectedStorage(): String = selectedStorage

    /**
     * 设置存储空间变化监听器
     */
    fun setOnStorageChangeListener(listener: (String) -> Unit) {
        onStorageChangeListener = listener
    }
    
    // TODO: 实现存储空间告警逻辑
    // 1. 监听存储空间变化，当剩余空间低于设定阈值时触发告警
    // 2. 保存用户选择的告警阈值到SharedPreferences或数据库
    // 3. 实现告警通知功能（Toast、Dialog或系统通知）
    // 4. 添加存储空间检测服务，定期检查剩余空间
    // 5. 实现告警历史记录功能

    /**
     * 设置开关变化监听器
     */
    fun setOnSwitchChangeListener(listener: (Boolean) -> Unit) {
        onSwitchChangeListener = listener
    }

    /**
     * 设置开关状态
     */
    fun setChecked(checked: Boolean) {
        switchView.isChecked = checked
    }

    /**
     * 获取开关状态
     */
    fun isChecked(): Boolean {
        return switchView.isChecked
    }

    /**
     * 显示存储空间下拉菜单
     */
    private fun showStorageDropdown() {
        if (storageOptions.isEmpty()) return

        val dropdownView = createStorageDropdownView()
        
        // 计算下拉菜单宽度
        val maxTextWidth = calculateMaxTextWidth()
        val minWidth = context.dpFromDimen(R.dimen.size_160)
        val maxWidth = width * 3 / 4
        val dropdownWidth = (maxTextWidth + context.dpFromDimen(R.dimen.spacing_22)).coerceIn(minWidth, maxWidth)
        
        popupWindow = PopupWindow(
            dropdownView,
            dropdownWidth,
            FrameLayout.LayoutParams.WRAP_CONTENT,
            true
        ).apply {
            isOutsideTouchable = true
            setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.storage_dropdown_background))
            elevation = 8f
        }

        // 计算下拉菜单位置
        val location = IntArray(2)
        getLocationOnScreen(location)
        val x = location[0] + width - dropdownWidth - context.dpFromDimen(R.dimen.spacing_80)
        val y = location[1]

        popupWindow?.showAtLocation(this, Gravity.NO_GRAVITY, x, y)
    }
    
    /**
     * 计算最大文本宽度
     */
    private fun calculateMaxTextWidth(): Int {
        val paint = android.graphics.Paint()
        paint.textSize = context.spFromDimen(R.dimen.font_16)
        return storageOptions.maxOfOrNull { 
            paint.measureText(it).toInt() 
        } ?: 0
    }

    /**
     * 创建存储空间下拉菜单视图
     */
    private fun createStorageDropdownView(): View {
        val container = LinearLayout(context).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(
                context.dpFromDimen(R.dimen.spacing_8),
                context.dpFromDimen(R.dimen.spacing_2),
                context.dpFromDimen(R.dimen.spacing_8),
                context.dpFromDimen(R.dimen.spacing_2)
            )
        }

        storageOptions.forEachIndexed { index, option ->
            val optionView = createStorageOptionView(option, index == storageOptions.lastIndex)
            val optionLP = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                topMargin = if(index == 0) context.dpFromDimen(R.dimen.spacing_6) else context.dpFromDimen(R.dimen.spacing_4)
                bottomMargin = if (index == storageOptions.lastIndex) context.dpFromDimen(R.dimen.spacing_6) else context.dpFromDimen(R.dimen.spacing_2)
                leftMargin = context.dpFromDimen(R.dimen.spacing_5)
                rightMargin = context.dpFromDimen(R.dimen.spacing_5)
            }
            container.addView(optionView, optionLP)
        }

        return container
    }

    /**
     * 创建存储空间选项视图
     */
    private fun createStorageOptionView(option: String, isLast: Boolean): View {
        val optionView = TextView(context).apply {
            text = option
            setTextColor(ContextCompat.getColor(context, R.color.text_primary))
            textSize = context.spFromDimen(R.dimen.font_12)
            setPadding(
                context.dpFromDimen(R.dimen.spacing_16),
                context.dpFromDimen(R.dimen.spacing_8),
                context.dpFromDimen(R.dimen.spacing_16),
                context.dpFromDimen(R.dimen.spacing_8)
            )
            isClickable = true
            isFocusable = true
            gravity = Gravity.CENTER
            maxLines = 1
            ellipsize = android.text.TextUtils.TruncateAt.END
            setTypeface(null, android.graphics.Typeface.BOLD)
        }

        // 设置选中状态背景
        if (option == selectedStorage) {
            optionView.background = ContextCompat.getDrawable(context, R.drawable.storage_option_selected_background)
        } else {
            optionView.background = ContextCompat.getDrawable(context, R.drawable.storage_option_background)
        }

        // 设置点击监听器
        optionView.setOnClickListener {
            setSelectedStorage(option)
            popupWindow?.dismiss()
            onStorageChangeListener?.invoke(option)
        }

        return optionView
    }
}
